package com.macoli.reflect_helper;

import android.os.Build;
import android.os.Looper;
import android.util.Log;
import android.util.Printer;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectHelper {

    public static Method getDeclaredMethod(Class<?> clz , String methodName , Class<?>[] params) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
            return NativeReflect.getInstance().getDeclaredMethod(clz , methodName , params) ;
        } else {
            Method metaGetDeclaredMethod = Class.class.getDeclaredMethod("getDeclaredMethod" , String.class , Class[].class) ;
            return (Method)metaGetDeclaredMethod.invoke(clz, methodName, params) ;
        }
    }


    public static Field getDeclaredField(Class<?> clz, String name) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
            return NativeReflect.getInstance().getDeclaredField(clz, name);
        } else {
            Method getDeclaredField = Class.class.getMethod("getDeclaredField", String.class);
            return (Field) getDeclaredField.invoke(clz, name);
        }
    }

    public static Constructor getDeclaredConstructor(Class<?> clz , Class<?>[] params) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

        return NativeReflect.getInstance().getDeclaredConstructor(clz , params) ;

    }


    public static void test() {
        try {
            Method m = ReflectHelper.getDeclaredMethod(Looper.class , "setTraceTag" , new Class[]{long.class}) ;
            m.invoke(Looper.getMainLooper() , 1000) ;
            Log.d("gggl" , m.toString()) ;
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }
}
